package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    ClazzMapper clazzMapper;

    @Override
    public Result pageQuery(StudentQueryParam student) {
        Integer currentPage = student.getPage();
        Integer pageSize = student.getPageSize();
        Page<Student> studentPage=Page.of(currentPage,pageSize);
        String name = student.getName();
        Integer degree = student.getDegree();
        Integer clazzId = student.getClazzId();
        this.lambdaQuery().like(!StrUtil.isBlank(name),Student::getName,name)
                .eq(Objects.nonNull(degree),Student::getDegree,degree)
                .eq(Objects.nonNull(clazzId),Student::getClazzId,clazzId)
                .page(studentPage);
        List<Student> studentList = studentPage.getRecords().stream().peek(student1 -> {
            Clazz clazz = clazzMapper.selectById(student1.getClazzId());
            if (Objects.nonNull(clazz)) {
                student1.setClazzName(clazz.getName());
            }
        }).toList();
        return Result.success(new PageResult<>(studentPage.getTotal(),studentList));
    }


    @Override
    public Result violation(Integer id, Integer score) {
        this.lambdaUpdate().setSql("violation_score=violation_score+"+score).setSql("violation_count=violation_count+1")
                .eq(Student::getId,id).update();
        return Result.success();
    }
}
